package userModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	redisjwts "KumquatDrivesServices/service/redis_jwts"
	"KumquatDrivesServices/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type UserForgotPwdRequest struct {
	OldPassword string `json:"oldPassword" binding:"required"`
	NewPassword string `json:"newPassword" binding:"required"`
}

func (UserModuleApi) UpdateUserPwd(c *gin.Context) {
	var req UserForgotPwdRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	accessToken := c.GetHeader("accessToken")
	refreshToken := c.GetHeader("refreshToken")
	userId := utils.GetUserId(c)
	if req.OldPassword == req.NewPassword {
		res.FailWithCode(res.ORIGINAL_PWD_SAME_NEW_PWD, c)
		return
	}
	var userModel model.UserModel
	if err := global.DB.Where("id = ?", userId).First(&userModel).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			res.FailWithCode(res.USER_NOT_EXIST, c)
			return
		}
		logrus.Errorf("UserModel.First error:%v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	bol, err := CheckPassword(userModel.Password, req.OldPassword)
	if err != nil {
		logrus.Errorf("CheckOldPassword error:%v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if !bol {
		res.FailWithCode(res.ORIGINAL_PWD_ERR, c)
		return
	}
	newpwd, hashpwdErr := HashPwd(req.NewPassword)
	if hashpwdErr != nil {
		logrus.Errorf("HashPwd error:%v", hashpwdErr)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if err = global.DB.Model(&userModel).Where("id = ?", userId).Update("password", newpwd).Error; err != nil {
		logrus.Errorf("UserModel.Update error:%v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	redisjwts.TokenBlack(accessToken, refreshToken)
	res.OkWithData(map[string]any{}, c)
}
